package com.example.securitydemo.dao;

import com.example.securitydemo.entity.Permission;
import com.example.securitydemo.entity.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhangyx
 * @desc
 * @date 2020/8/18 9:53
 **/
@Repository
public class UserDao {

    @Autowired
    JdbcTemplate jdbcTemplate;

    //根据用户名查询用户
    public UserDto getUserByUsername(String username){
        String sql = "select id,username,password from t_user where username = ?";
        //连接数据库查询数据
        List<UserDto> userDtos = jdbcTemplate.query(sql,new Object[]{username},new BeanPropertyRowMapper<>(UserDto.class));
        if(userDtos!=null && userDtos.size()>0){
            return userDtos.get(0);
        }
        return null;
    }

    //根据用户名查询权限
    public List<String> getPermissionByUsername(String userId){
            String sql = "SELECT\n" +
                    "\t*\n" +
                    "FROM\n" +
                    "\tt_permission t1\n" +
                    "LEFT JOIN t_role_permission t2 ON t1.id = t2.permission_id\n" +
                    "LEFT JOIN t_user_role t3 ON t2.role_id = t3.role_id\n" +
                    "WHERE\n" +
                    "\tt3.user_id = ?";
            List<Permission> permissions = jdbcTemplate.query(sql,new Object[]{userId},new BeanPropertyRowMapper<>(Permission.class));
            List<String> codes = permissions.stream().map(Permission::getCode).collect(Collectors.toList());
            return codes;
    }
}
